package com.yf.dxapp.module.app;

import java.io.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class TextFileMerger {

    public static void mergeTextFiles(String folderPath, String outputFilePath) {
        try {
            List<Path> txtFiles = new ArrayList<>();

            // 使用Files.walk遍历文件夹
            Files.walk(Paths.get(folderPath))
                    .filter(Files::isRegularFile) // 过滤出普通文件
                    .filter(p -> p.toString().endsWith(".sql")) // 过滤出.txt文件
                    .forEach(txtFiles::add); // 将符合条件的文件添加到列表中

            try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFilePath), StandardCharsets.UTF_8)) {
                for (Path txtFile : txtFiles) {
                    try (BufferedReader reader = Files.newBufferedReader(txtFile, StandardCharsets.UTF_8)) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            writer.write(line);
                            writer.newLine(); // 写入换行符
                        }
                        // 在每个文件内容后可选择性地添加一个额外的空行或其他分隔符
                        // writer.newLine();
                    }
                }
            }

            System.out.println("Files merged successfully to: " + outputFilePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 示例用法
        String folderPath = "F:\\code\\myself\\新建文件夹\\sql"; // 替换为实际的文件夹路径
        String outputFilePath = "F:\\code\\myself\\新建文件夹\\sql\\merged.txt"; // 替换为合并后文件的路径
        mergeTextFiles(folderPath, outputFilePath);
    }
}